package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.http.HttpUser;
import com.lishe.lishe.lishe.module.excitation.bean.company.JoinCompany;
import com.lishe.lishe.lishe.module.excitation.bean.company.SearchCompany;
import com.lishe.lishe.lishe.module.excitation.bean.user.UserObject;
import com.lishe.lishe.lishe.module.excitation.presenter.ExcitationPresenter;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * Created by yang on 2017/11/20.
 * 加入企业
 */

public class JoinCompanyActivity extends BaseActivity implements View.OnClickListener {

    public static final int SEARCH_COMPANY = 1001;

    public static void jump(Activity activity, UserObject user) {
        Intent intent = new Intent(activity, JoinCompanyActivity.class);
        intent.putExtra("UserObject", user);
        activity.startActivity(intent);
    }

    private TextView mTextTel,
            mTextTitle,
            mTextComName,
            mTextReApply,
            mTextTip,
            mTextKnown,
            mTextReply;
    private Button mButtonBack;
    private EditText mEditUserName;
    private LinearLayout mLinearCom,
            mLinearApply;

    private String mStrEmpName;
    private SearchCompany mSearchCompany;
    private UserObject mUser = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join_company);
        mUser = (UserObject) getIntent().getSerializableExtra("UserObject");
        initView();
        setListener();
        if (mUser != null) {
            updateView();
        } else {
            getUserinfo();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == SEARCH_COMPANY) {
                mSearchCompany = data.getParcelableExtra("SearchCompany");

                if (mSearchCompany != null) {
                    mTextComName.setText(mSearchCompany.getComName());
                }
            }
        }
    }

    private void updateView() {
        mTextTel.setText(mUser.getPhoneNo());

        if ((!TextUtils.isEmpty(mUser.getEmpStatus())) && mUser.getEmpStatus().equals("0")) {//审核不通过
            mTextKnown.setVisibility(View.VISIBLE);
            mTextTip.setText(R.string.company_no_through_your_apply);
        } else {
            mTextKnown.setVisibility(View.GONE);
            mTextTip.setText(R.string.have_apply_join_please_wait);
        }

        if (mUser.getComId().equals("-1") || mUser.getEmpStatus() == null) {//未加入企业
            mTextReply.setVisibility(View.VISIBLE);
            mLinearApply.setVisibility(View.GONE);
        } else if (mUser.getEmpStatus().equals("-1")) {//企业未确认)
            mSearchCompany = new SearchCompany();
            mSearchCompany.setComId(mUser.getComId());
            mSearchCompany.setComName(mUser.getComName());
            mTextReply.setVisibility(View.GONE);
            mLinearApply.setVisibility(View.VISIBLE);
            mEditUserName.setText(mUser.getEmpName());
            mTextComName.setText(mUser.getComName());

            mTextTitle.setText(R.string.mine_apply);
            mEditUserName.setEnabled(false);
        }
    }

    private void initView() {
        mTextTel = findViewById(R.id.tel);
        mTextReply = findViewById(R.id.apply);
        mTextComName = findViewById(R.id.comName);
        mEditUserName = findViewById(R.id.user_name);
        mButtonBack = findViewById(R.id.title_left_button);
        mTextTitle = findViewById(R.id.title_text_title);
        mLinearCom = findViewById(R.id.ll_com);
        mLinearApply = findViewById(R.id.ll_apply);
        mTextReApply = findViewById(R.id.re_apply);
        mTextTip = findViewById(R.id.tip);
        mTextKnown = findViewById(R.id.known);

        mTextTitle.setText(R.string.join_my_company);
        if (mUser == null) {
            mLinearApply.setVisibility(View.GONE);
            mTextReply.setVisibility(View.VISIBLE);
            mTextTel.setText(SharedPreferencesUtils.getPhone(JoinCompanyActivity.this));
        } else {
            updateView();
        }
    }

    private void setListener() {
        mButtonBack.setOnClickListener(this);
        mTextReply.setOnClickListener(this);
        mLinearCom.setOnClickListener(this);
        mTextReApply.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_button:
                finish();
                break;
            case R.id.apply:
                mStrEmpName = mEditUserName.getText().toString().trim();
                if (mSearchCompany != null) {
                    if(!TextUtils.isEmpty(mStrEmpName)) {
                        joinCompany();
                    }else{
                        toast(getString(R.string.please_input_your_name));
                    }
                }else{
                    toast(getString(R.string.please_input_your_company_name));
                }
                break;
            case R.id.ll_com:
                if (mLinearApply.getVisibility() == View.GONE)
                    SearchCompanyActivity.jump(JoinCompanyActivity.this);
                break;
            case R.id.re_apply:
                mLinearApply.setVisibility(View.GONE);
                mTextReply.setVisibility(View.VISIBLE);

                mTextTitle.setText(R.string.join_my_company);
                mEditUserName.setEnabled(true);
                break;
        }
    }

    private void joinCompany() {
        ExcitationPresenter.getInstance().joinCom(Globals.getToken(), mSearchCompany.getComId(), mStrEmpName, new DataResponseListener<JoinCompany>() {
            @Override
            public void onPrepare() {
                super.onPrepare();
                LoadingUtils.createLoadingDialog(JoinCompanyActivity.this, "申请中...", false);
            }

            @Override
            public void onSuccess(JoinCompany dataResponse) {
                LoadingUtils.closeDialog();
                mTextReply.setVisibility(View.GONE);
                mLinearApply.setVisibility(View.VISIBLE);
                upToken(mSearchCompany.getComId());
            }

            @Override
            public void onFail(String failMessage) {
                LoadingUtils.closeDialog();
                toast(failMessage);
            }

            @Override
            public void onError(Throwable e) {
                LoadingUtils.closeDialog();
                e.printStackTrace();
            }
        });
    }

    private void getUserinfo() {
        try {
            ExcitationPresenter.getInstance().getUserInfo(Globals.getToken(), new DataResponseListener<UserObject>() {
                @Override
                public void onSuccess(UserObject dataResponse) {
                    mUser = dataResponse;
                    updateView();
                }

                @Override
                public void onFail(String failMessage) {
                    toast(failMessage);
                }

                @Override
                public void onError(Throwable e) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 登陆企业后更新token
     */
    private void upToken(String comId) {
        String token = Globals.getToken();
        HttpUser.getUpToken(token, comId, responseHandler);
    }

    AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String data = new String(responseBody);
            if (data != null) {
                try {
                    String msg = "";
                    JSONObject jsonObject = new JSONObject(data);
                    if (jsonObject.optInt("errcode") == 0 && jsonObject.optInt("result") == 100) {
                        finish();
                        String mtoken = jsonObject.optString("data");
                        msg = jsonObject.optString("msg");
                        if (!TextUtils.isEmpty(mtoken) && !mtoken.equals("null")) {
                            SharedPreferencesUtils.saveToken(mtoken, JoinCompanyActivity.this);
                        }
                    } else {
                        toast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast("企业登录失败！" + new String(responseBody));
        }
    };
}
